package com.sf.leetcode.primary_alogrithm;

import javax.print.DocFlavor;

public class myAtoi {

    public static void main(String[] args) {
        String s = "words and 987";
//        String s = "   -42";
//        String s = "4193 with words";
//        String s ="-91283472332";
        System.out.println(myAtoi(s));
    }


    public static int myAtoi(String s) {
        String t = s.replaceAll(" ","");
        char[] ch = t.toCharArray();
        if(Character.isLetter(ch[0])){
            return 0;
        }
        int num = 0;
        int flag = 1;
        if(ch[0] != '-'){
            for (int i = 0; i < ch.length; i++) {
                if(Character.isDigit(ch[i])){
                    num = num * 10;
                    num = num + Integer.parseInt(String.valueOf(ch[i]));
                    if (num > 214748364) {
                        return Integer.MAX_VALUE;
                    }
                }else {
                    return num;
                }
            }
        }else {
            flag = -1;
            for (int i = 1; i < ch.length; i++) {
                if(Character.isDigit(ch[i])) {
                    num = num * 10;
                    num = num + Integer.parseInt(String.valueOf(ch[i]));
                }
            }
        }
        int end = 214748364;
        if(num > end){
            return Integer.MIN_VALUE;
        }else {
            return num * flag;
        }
    }
}
